<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="obj.uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="obj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="obj.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="remove(index)">删除</button>
            <button @click="setList(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          uname: "tom",
          age: 15,
          sex: "男",
        },
        {
          uname: "Jon",
          age: 16,
          sex: "女",
        },
      ],
      obj: {
        uname: "",
        age: "",
        sex: "",
      },
      isAll: true,
      i: null,
    };
  },
  methods: {
    remove(index) {
      this.list.splice(index, 1);
    },
    add() {
      if (this.obj.uname === "" || this.obj.sex === "" || this.obj.age === "")
        return;
      if (this.isAll) {
        const newobj = JSON.parse(JSON.stringify(this.obj));
        this.list.push(newobj);
        this.obj.uname = "";
        this.obj.age = "";
        this.obj.sex = "";
      } else {
        this.list[this.i].uname = this.obj.uname;
        this.list[this.i].age = this.obj.age;
        this.list[this.i].sex = this.obj.sex;
        this.obj.uname = "";
        this.obj.age = "";
        this.obj.sex = "";
        this.isAll = true;
      }
    },
    setList(index) {
      this.obj.uname = this.list[index].uname;
      this.obj.age = this.list[index].age;
      this.obj.sex = this.list[index].sex;
      this.isAll = false;
      this.i = index;
    },
  },
};
</script>
